<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import treeSelect from '@/components/tree-select-edl/index.vue'
import wjzs from '@/components/wjzs.vue'
// import hwQzb from '@/components/hw-qzb/hw-qzb.vue'
import mtQzb from '@/components/mt-qzb/index.vue'
import dlglService from '@/api/dlgl'
import { getFldm } from '@/utils/get-fldm'
import { cloneDeep } from 'lodash'
import gdglService from '@/api/gdgl'
import jzsmService from '@/api/jzsm'
import { JzsmListOutputDTO } from '@/api/jzsm-dto'
import { useMainStore } from '@/store/main'
import printFn from '@/utils/print'
const store = useMainStore()

// 送扫人类型
interface YjrItem {
  id: string
  mc: string
}

// 入参
const emit = defineEmits(['refresh'])

onMounted(() => {
  // 获取签名方式
  getQmfs()
  // 获取送扫人
  getYjr()
})
/*
 * 打开弹框
 */
//
const loading = ref<boolean>(false)
const title = ref<string>('')
// 当前类型
const typeValue = ref<string>('')
// 输入数据
const inputValue = ref<string>('')
// 签名方式
const qmfsValue = ref<string>('gd0230002')
const qmfsmc = ref<string>('')
// 文件预览地址
const pdfUrl = ref<string>('')
const dialogVisible = ref<boolean>(false)
const openDialog = (type: string, arr: JzsmListOutputDTO[]) => {
  step.value = 1
  typeValue.value = type // 'js' | 'gh'
  title.value = type === 'js' ? '接收' : '归还'
  yjrObj.value = {
    id: '',
    mc: '',
  }
  pdfUrl.value = ''
  tableData.value = cloneDeep(arr)
  dialogVisible.value = true
}

/**
 * 当前步骤
 */
const step = ref<number>(1)

const wjxhValue = ref()
/**
 * 表格
 */
const tableData = ref<any[]>([])

/**
 * 添加表格项
 */
const addRow = () => {
  if (!inputValue.value) {
    ElMessage.warning('请输入部门受案号')
    return
  }
  typeValue.value === 'js' ? queryJsstclAjxx() : queryGhstclAjxx()
}

/**
 * 接收查询列表
 */
const queryJsstclAjxx = () => {
  // 查询数据
  const params = {
    bmsahs: [inputValue.value],
  }
  jzsmService
    .queryAjxxlbbybmsah(params)
    .then((res) => {
      if (res.data?.length) {
        const value = {
          ...res.data[0],
        }
        // 校验是否已经添加
        const obj = tableData.value.find((item) => item.ajbh === value.ajbh)
        if (obj) {
          ElMessage.warning('已存在该条数据')
        } else {
          inputValue.value = ''
          tableData.value.push(value)
        }
      } else {
        ElMessage.warning('未查询到相关案件信息')
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

/**
 * 归还查询列表
 */
const queryGhstclAjxx = () => {
  // 查询数据
  const params = {
    bmsahs: [inputValue.value],
  }
  jzsmService
    .queryGdsmbybmsahList(params)
    .then((res) => {
      if (res.data?.length) {
        const value = {
          ...res.data[0],
        }
        // 校验是否已经添加
        const obj = tableData.value.find((item) => item.ajbh === value.ajbh)
        if (obj) {
          ElMessage.warning('已存在该条数据')
        } else {
          inputValue.value = ''
          tableData.value.push(value)
        }
      } else {
        ElMessage.warning('未查询到相关案件信息')
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}
/**
 * 删除表格项
 */
const deleteRow = (index: number) => {
  tableData.value.splice(index, 1)
}

/**
 * 获取集中扫描接收交接单
 */
const jsjjdParams = ref<any>()
const getJzsmjsjjd = (flag?: boolean) => {
  const params = {
    dwmc: store.$state.userInfo?.dwmc,
    list: tableData.value.map((el, index) => {
      return {
        ajmc: el.ajmc,
        ajsl: el.ajsl,
        bmsah: el.bmsah,
        cbbmmc: el.cbbmmc,
        index: `${index}`,
        jsrbh: store.userInfo.ryid,
        jsrxm: store.userInfo.xm,
        ssrbh: yjrObj.value.id,
        ssrxm: yjrObj.value.mc,
        zpsl: el.zpsl,
      }
    }),
    ssrdzqmwjxh: flag ? wjxhValue.value : '',
  }
  jsjjdParams.value = params
  gdglService
    .getJzsmjsjjd(params)
    .then((res) => {
      if (res.data.type === 'application/json') {
        const reader = new FileReader()
        reader.onload = () => {
          const jsonData =
            typeof reader.result === 'string' ? JSON.parse(reader.result) : reader.result
          ElMessage({ type: 'warning', message: jsonData.message })
        }
        reader.readAsText(res.data)
      } else {
        pdfUrl.value = window.URL.createObjectURL(res.data)
        nextTick(() => {
          wjzsRef.value?.init()
        })
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

const printJsjjd = () => {
  const params = {
    fileSource: '2',
    localFilePathList: [],
    fileName: '集中扫描接收交接单.pdf',
    loadingHeader: {},
    loadingParam: jsjjdParams.value,
    loadingUrl: `${window.IPCONFIG}/api/gdgl/getJzsmjsjjd`,
    requestMethodName: 'POST',
  }
  printFn(params)
}

const printGhjjd = () => {
  const params = {
    fileSource: '2',
    localFilePathList: [],
    fileName: '归还实体归档交接单.pdf',
    loadingHeader: {},
    loadingParam: ghjjdParams.value,
    loadingUrl: `${window.IPCONFIG}/api/gdgl/getSmcljjd`,
    requestMethodName: 'GET',
    preUrl: `${window.IPCONFIG}/api/gdgl/getSmcljjdxh`,
    preMethodName: 'POST',
    preParam: ghjjdPreParams.value,
    preResField: 'smcljjdxh',
  }
  printFn(params)
}
const print = () => {
  typeValue.value === 'js' ? printJsjjd() : printGhjjd()
}
/**
 * 下一步
 */
const next = async () => {
  if (tableData.value.length === 0) {
    ElMessage.warning('请添加案件')
    return
  }

  if (!yjrObj.value.id) {
    ElMessage.warning(`请选择业务部门${typeValue.value === 'js' ? '送扫人' : '签收人'}`)
    return
  }
  step.value = 2
  typeValue.value === 'js' ? getJzsmjsjjd() : getSmcljjd()
}
/**
 * 上一步
 */
const prev = () => {
  step.value = 1
  wjxhValue.value = ''
  fileRef.value.value = ''
}

/**
 * 获取签名方式
 */
const qmfsList = ref()
const getQmfs = async () => {
  qmfsList.value = await getFldm('gd023')
  if (qmfsList.value.length) {
    qmfsValue.value = qmfsList.value[0].dm
    qmfsmc.value = qmfsList.value[0].mc
  }
}

/**
 * 签名方式change
 */
const qmfsChange = (val: string) => {
  pdfUrl.value = ''
  yjrObj.value.id = ''
  yjrObj.value.mc = ''
  const obj = qmfsList.value.find((item: any) => item.dm === val)
  qmfsmc.value = obj ? obj.mc : ''
}

/**
 * 获取送扫人
 */
const yjrObj = ref<YjrItem>({
  id: '',
  mc: '',
})
const yjrList = ref<any[]>([])
const getYjr = () => {
  // 查询数据
  const params = {
    code: '',
    dwbm: store.$state.userInfo?.dwbm,
    rymc: '',
  }
  dlglService
    .queryRyybmTree(params)
    .then((res) => {
      if (res.data?.list) {
        yjrList.value = res.data.list
        resetTree(yjrList.value)
      } else {
        yjrList.value = []
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

/**
 * 重构树
 */
const resetTree = (arr: any[]) => {
  arr.forEach((el) => {
    el.dm = el.bmbm || el.rybm
    el.mc = el.bmmc || el.rymc
    if (el.list?.length) {
      el.children = el.list
      resetTree(el.children)
    }
  })
}

/**
 * 树点击
 */
const nodeChange = (val: string, node: any, mc: string) => {
  const value = yjrObj.value as any
  value[mc] = node.mc
}

/**
 * 生成归还实体归档交接单
 */
const ghjjdPreParams = ref<any>()
const ghjjdParams = ref<any>()
const getSmcljjd = async (flag?: boolean) => {
  const params = {
    jzsmjlbhList: tableData.value.map((el) => el.jzsmjlbh),
  }
  ghjjdPreParams.value = params
  jzsmService
    .getSmcljjdxh(params)
    .then((res) => {
      if (res) {
        const xh = res.data
        getSmjjd(xh, flag)
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}
const wjzsRef = ref()
const getSmjjd = (val: string, flag?: boolean) => {
  const params = {
    smcljjdxh: val,
    dwmc: store.userInfo.dwmc,
    qsrdzqmwjxh: flag ? wjxhValue.value : '',
  }
  ghjjdParams.value = {
    dwmc: store.userInfo.dwmc,
    qsrdzqmwjxh: flag ? wjxhValue.value : '',
  }
  jzsmService.getSmcljjd(params).then((res) => {
    if (res.data.type === 'application/json') {
      const reader = new FileReader()
      reader.onload = () => {
        const jsonData =
          typeof reader.result === 'string' ? JSON.parse(reader.result) : reader.result
        ElMessage({ type: 'warning', message: jsonData.message })
      }
      reader.readAsText(res.data)
    } else {
      pdfUrl.value = window.URL.createObjectURL(res.data)
      dialogVisible.value = true
      nextTick(() => {
        wjzsRef.value?.init()
      })
    }
  })
}

/**
 * 接收实体案卷
 */
const receiveStaj = () => {
  const params = paramsValue.value
  jzsmService
    .receiveJzsmcl(params)
    .then(() => {
      ElMessage.success('接收成功')
      if (qmfsValue.value === 'gd0230001') {
        getJzsmjsjjd(true)
        step.value = 2
      } else {
        closeDialog()
      }
      emit('refresh')
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

/**
 * 归还实体卷宗
 */
const updateGhstcl = (flag?: boolean) => {
  const params = paramsValue.value
  jzsmService
    .ghJzsmcl(params)
    .then(() => {
      ElMessage.success('归还成功')
      // 线上签名
      if (flag) {
        step.value = 2
        getSmcljjd(true)
      } else {
        closeDialog()
      }
      emit('refresh')
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

/*
 * 打开汉王签名板
 */
const mtQzbRef = ref()
const handleQm = () => {
  mtQzbRef.value.openDialog()
  // hwQzbRef.value.socketBegin()
}
/*
 * 保存数据
 */
const hwQzbRef = ref()
const paramsValue = ref<any>()

const saveData = async () => {
  if (tableData.value.length === 0) {
    ElMessage.warning('请添加案件')
    return
  }
  if (!yjrObj.value.id) {
    ElMessage.warning(`请选择业务部门${typeValue.value === 'js' ? '送扫人' : '签收人'}`)
    return
  }
  if (!mtQzbRef.value.qmtp) {
    ElMessage.warning(`请${typeValue.value === 'js' ? '送扫人' : '签收人'}签名`)
    return
  }
  let wjxh = ''
  if (qmfsValue.value === 'gd0230001') {
    // 线上
    const file = base64ToFile(mtQzbRef.value.qmtp, '电子签名')
    // 上传文件
    wjxh = await singleUploadFile(file)
    // 预览文件
    wjxhValue.value = wjxh
    // 提交
    submit(true)
  }
}

/**
 * 提交
 */
const submit = (flag?: boolean) => {
  if (!wjxhValue.value) {
    ElMessage.warning('未找到文件序号')
    return
  }

  // 参数组装
  if (typeValue.value === 'js') {
    const jzsmxxList = tableData.value.map((el) => {
      return {
        ajbh: el.ajbh,
        bmsah: el.bmsah,
        gdjlbh: el.gdjlbh,
        zpsl: el.smzpsl,
        zzajsl: el.smajsl,
      }
    })
    paramsValue.value = {
      jzsmxxList: jzsmxxList,
      wjxh: wjxhValue.value || pdfUrl.value,
      ssrqmfsdm: qmfsValue.value,
      ssrqmfsmc: qmfsmc.value,
      ssrbh: yjrObj.value.id,
      ssrxm: yjrObj.value.mc,
    }
  } else {
    const smjlxxList = tableData.value.map((el) => {
      return {
        jzsmjlbh: el.jzsmjlbh,
      }
    })
    paramsValue.value = {
      smjlxxList: smjlxxList,
      wjxh: wjxhValue.value || pdfUrl.value,
      qsrqmfsdm: qmfsValue.value,
      qsrqmfsmc: qmfsmc.value,
      qsrbh: yjrObj.value.id,
      qsrxm: yjrObj.value.mc,
    }
  }
  typeValue.value === 'js' ? receiveStaj() : updateGhstcl(flag)
}
/**
 * base64转换file
 */
const base64ToFile = (base64: any, fileName: string) => {
  const arr = base64.split(',')
  const mime = arr[0].match(/:(.*?);/)[1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)

  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], fileName, { type: mime })
}

/**
 * 上传文件
 */
const singleUploadFile = async (file: any) => {
  const formData = new FormData()
  formData.append('file', file)
  const res = await gdglService.singleUploadFile(formData).catch((err) => {
    !err.isError && ElMessage({ type: 'warning', message: err.message })
    return {
      data: {
        wjxh: '',
      },
    }
  })
  return res.data?.wjxh || ''
}
const fileRef = ref()
// 点击上传按钮
const submitImg = () => {
  fileRef.value.multiple = false
  fileRef.value.accept = '.pdf'
  fileRef.value.click()
}

const uploadFile = async (e: any) => {
  const file = e.target.files[0]
  if (!file.name.includes('pdf')) {
    ElMessage({ type: 'error', message: '只能上传pdf文件' })
    return
  }
  wjxhValue.value = await singleUploadFile(file)
  if (wjxhValue.value) {
    const fileType = file.type
    const blob = new Blob([file], { type: fileType || 'application/*' })
    const blobUrl = window.URL.createObjectURL(blob)
    pdfUrl.value = blobUrl
    nextTick(() => {
      wjzsRef.value?.init()
    })
  }
}

// 下载按钮
const download = () => {
  if (typeValue.value === 'js') {
    const downloadElement = document.createElement('a')
    downloadElement.href = pdfUrl.value
    downloadElement.download = `材料交接单.pdf`
    document.body.appendChild(downloadElement)
    downloadElement.click() //点击下载
    document.body.removeChild(downloadElement) //下载完成移除元素
  } else {
    const params = {
      jzsmjlbhList: tableData.value.map((el) => el.jzsmjlbh),
    }
    jzsmService
      .getSmcljjd(params)
      .then((res) => {
        if (res) {
          const xh = res.data
          const url = `${window.IPCONFIG}/api/gdgl/getSmcljjd?smcljjdxh=${xh}&dwmc=${
            store.userInfo.dwmc
          }${qmfsValue.value === 'gd0230001' ? '&qsrdzqmwjxh=' + wjxhValue.value : ''}`
          const downloadElement = document.createElement('a')
          downloadElement.href = url
          downloadElement.download = `材料交接单.pdf`
          document.body.appendChild(downloadElement)
          downloadElement.click() //点击下载
          document.body.removeChild(downloadElement) //下载完成移除元素
        }
      })
      .catch((err) => {
        !err.isError && ElMessage({ type: 'warning', message: err.message })
      })
  }
}

const closeDialog = () => {
  tableData.value = []
  inputValue.value = ''
  wjxhValue.value = ''
  fileRef.value.value = ''
  pdfUrl.value = ''
  qmfsValue.value = 'gd0230001'
  dialogVisible.value = false
}

defineExpose({ openDialog })
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    v-if="dialogVisible"
    :title="`${title}材料`"
    width="80%"
    :close-on-click-modal="false"
    @closed="closeDialog"
  >
    <div class="dialog-box">
      <div class="aj-choose-box" v-if="step === 1">
        <div class="aj-choose-left">
          <div class="table-wrap">
            <el-table :data="tableData" height="100%">
              <el-table-column type="index" label="序号" width="55" />
              <el-table-column prop="ajmc" label="案件名称" min-width="160" show-overflow-tooltip />
              <el-table-column
                prop="bmsah"
                label="部门受案号"
                min-width="280"
                show-overflow-tooltip
              />
              <el-table-column
                prop="cbbmmc"
                label="承办部门"
                min-width="160"
                show-overflow-tooltip
              />
              <el-table-column prop="cbjcg" label="检察官" min-width="160" show-overflow-tooltip />
              <el-table-column label="操作" width="60" fixed="right">
                <template #default="scope">
                  <el-link type="primary" :underline="false" @click="deleteRow(scope.$index)"
                    >删除</el-link
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="bmsah-box">
            <span>部门受案号</span>
            <el-input v-model="inputValue" placeholder="请输入" clearable />
            <el-button type="primary" @click="addRow">添加</el-button>
          </div>
        </div>

        <div class="aj-choose-right">
          <div class="qmfs-box">
            <div class="yjr-label">签名方式:</div>
            <el-select v-model="qmfsValue" @change="qmfsChange">
              <el-option v-for="item in qmfsList" :key="item.dm" :label="item.mc" :value="item.dm">
              </el-option>
            </el-select>
          </div>
          <div class="qm-box">
            <div class="yjr-box">
              <div class="yjr-label">
                请选择业务部门{{ typeValue === 'js' ? '送扫人' : '签收人' }}:
              </div>
              <tree-select
                v-model="yjrObj.id"
                :options="yjrList"
                node-key="ryid"
                @node-change="(data:string, node:any)=> nodeChange(data, node,'mc')"
              ></tree-select>
            </div>
            <div class="yjrqm-box" v-if="qmfsValue === 'gd0230001'">
              <div class="yjr-label">
                请业务部门{{ typeValue === 'js' ? '送扫人' : '签收人' }}签名:
                <el-button style="min-width: auto" @click="handleQm">签名</el-button>
              </div>
              <div class="canvas-box">
                <mtQzb ref="mtQzbRef"></mtQzb>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="pdf-box" v-else-if="step === 2">
        <!-- <pdf-preview :src="pdfUrl" />-->
        <wjzs ref="wjzsRef" wjlx="pdf" :url="pdfUrl" />
      </div>
      <input style="display: none" type="file" @change="uploadFile" ref="fileRef" />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="next" v-if="step === 1 && qmfsValue !== 'gd0230001'"
          >下一步</el-button
        >
        <el-button type="primary" @click="prev" v-if="step === 2 && qmfsValue !== 'gd0230001'"
          >上一步</el-button
        >
        <el-button
          type="primary"
          @click="saveData"
          :loading="loading"
          v-if="step === 1 && qmfsValue === 'gd0230001'"
          >确定</el-button
        >
        <el-button type="primary" v-if="step === 2" @click="download">下载</el-button>
        <el-button type="primary" v-if="step === 2" @click="print">打印</el-button>
        <el-button type="primary" v-if="step === 2 && !wjxhValue" @click="submitImg"
          >上传</el-button
        >
        <el-button
          type="primary"
          @click="submit()"
          :loading="loading"
          v-if="step === 2 && wjxhValue && qmfsValue !== 'gd0230001'"
          >确定</el-button
        >
        <el-button @click="closeDialog">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.dialog-box {
  width: 100%;
  height: 70vh;
}
.bmsah-box {
  display: flex;
  align-items: center;
  margin-top: 10px;
  .el-input {
    margin: 0 10px;
    width: 300px;
  }
}
.number-input {
  width: 70px;
}
.aj-choose-box {
  width: 100%;
  height: 100%;
  display: flex;
  // flex-direction: column;

  .aj-choose-left {
    width: calc(100% - 450px);
    height: 100%;
    padding: 10px;
    border: 1px solid #dae4f1;
    .table-wrap {
      height: calc(100% - 45px);
    }
  }

  .aj-choose-right {
    width: 440px;
    flex: 1;
    display: flex;
    flex-direction: column;
    margin-left: 10px;
    padding: 10px;
    border: 1px solid #dae4f1;
  }

  .qmfs-box {
    .yjr-label {
      height: 34px;
      line-height: 34px;
      color: #526a89;
    }
    .el-select {
      width: 200px;
    }
  }

  .qm-box {
    display: flex;
    flex-direction: column;
    flex: 1;
    flex-shrink: 0;
    .yjrqm-box {
      height: 300px;
      float: left;
      .yjr-label {
        margin-bottom: 5px;
      }
    }
    .yjr-box {
      width: 80%;
      float: left;
      margin-bottom: 5px;
    }
    .yjr-label {
      height: 34px;
      line-height: 34px;
      color: #526a89;
    }
  }
  .canvas-box {
    width: 100%;
    height: calc(100% - 40px);
    border: 1px solid #dae4f1;
    overflow: hidden;
  }
}

.pdf-box {
  width: 100%;
  height: 100%;
}
</style>
